﻿using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Spark.AspNetCore;
using Spark.Core.Exceptions;

namespace Spark.Config.Api.AppCode.Sms
{
    public static class SmsServiceExtensions
    {
        public static SparkBuilder AddSmsService(this SparkBuilder builder, IConfiguration configuration, string section = "")
        {
            if (string.IsNullOrWhiteSpace(section))
                section = "GlobalConfig:Sms";
            builder.Services.Configure<SmsConfig>(configuration.GetSection(section));
            builder.Services.AddSingleton<YunXinShiSMS>();
            builder.Services.AddSingleton(provider =>
            {
                ISms Func(SmsType mode)
                {
                    switch (mode)
                    {
                        case SmsType.YunXinShi:
                            return provider.GetService<YunXinShiSMS>();

                        default:
                            throw new SparkException("无法识别的type");
                    }
                }
                return (Func<SmsType, ISms>)Func;
            });
            return builder;
        }

        public static SparkBuilder AddSmsService(this SparkBuilder builder, Action<SmsConfig> action)
        {
            if (action == null)
                throw new ArgumentNullException(nameof(action));

            builder.Services.Configure(action);
            builder.Services.AddSingleton<YunXinShiSMS>();
            builder.Services.AddSingleton(provider =>
            {
                ISms Func(string mode)
                {
                    switch (mode)
                    {
                        case "yxs":
                            return provider.GetService<YunXinShiSMS>();

                        default:
                            throw new SparkException("无法识别的type");
                    }
                }
                return (Func<string, ISms>)Func;
            });
            return builder;
        }
    }
}